package com.black.gateway.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

@Component
public class JwtUtil {

    @Value("${share.auth.signingKey}")
    public String signingKey;

    /**
     * 由字符串生成加密key
     * @return SecretKey
     */
    private SecretKey generalKey(){
        byte[] encodedKey = signingKey.getBytes();
        return new SecretKeySpec(encodedKey, 0, encodedKey.length, "HS256");
    }

    /**
     * 解密jwt
     *
     * @param token 鉴权的令牌
     * @return Claims
     */
    public Claims parseJWT(String token) {
        SecretKey key = generalKey();  //签名秘钥，和生成的签名的秘钥一模一样
        return Jwts.parser()  //得到DefaultJwtParser
                .setSigningKey(key)                 //设置签名的秘钥
                .parseClaimsJws(token).getBody();
    }


}
